import React, { useState, useEffect, useMemo, useCallback } from 'react';
import { Switch, Tooltip, Button, message } from 'antd';
import { QuestionCircleOutlined, SettingOutlined } from '@ant-design/icons';
import VirtualAvatarModal from './VirtualAvatarModal';
import metahumanService from '@/api/services/metahumanService';
import { MetahumanAvatar } from '@/types/metahuman';
import { useMetahumanStore } from '@/store/metahumanStore';
import { SvgIcon } from '@/components/icon';
import TipDesc from '@/components/tipDesc/tipDesc';
import '../index.css'

interface VirtualAvatarConfigProps {
  isPreview?: boolean;
  enabled?: boolean;
  onToggle?: (enabled: boolean) => void;
  avatarName?: string;
  voiceType?: string;
  onAvatarChange?: (avatarName: string, voiceType: string, avatarId: string, speakerId: string) => void;
}

const VirtualAvatarConfig: React.FC<VirtualAvatarConfigProps> = ({
  isPreview = false,
  onToggle,
  onAvatarChange
}) => {
  // 使用 metahumanStore 管理状态
  const {
    virtualAvatarEnabled,
    virtualAvatarName,
    virtualAvatarVoice,
    setVirtualAvatarEnabled,
    setVirtualAvatarName,
    setVirtualAvatarVoice,
    setVirtualAvatarUrl,
    setVirtualAvatarId,
    stop,
    permissionConfig,
    setVirtualSpeakerId
  } = useMetahumanStore();

  const [modalVisible, setModalVisible] = useState(false);
  const [avatarOptions, setAvatarOptions] = useState<MetahumanAvatar[]>([]);
  const [loading, setLoading] = useState(false);

  // 是否满足配额
  const isQuota = useMemo(() => permissionConfig?.metahumanQuota, [permissionConfig]);

  // 获取虚拟形象数据
  const fetchAvatarOptions = useCallback(async () => {
    try {
      console.log('fetchAvatarOptions')
      setLoading(true);
      const response = await metahumanService.getMetahumanAvatars();

      if (response.avatars && response.avatars.length > 0) {
        const transformedAvatars = response.avatars;
        setAvatarOptions(transformedAvatars);
      } else {
        message.info('未获取到虚拟形象数据，使用默认配置');
      }
    } catch (error) {
      console.error('获取虚拟形象数据失败:', error);
    } finally {
      setLoading(false);
    }
  }, [setVirtualAvatarName, setVirtualAvatarVoice, onAvatarChange]);

  // 组件挂载时获取数据
  useEffect(() => {
    fetchAvatarOptions();
  }, []);

  // 使用 useMemo 缓存当前形象的头像图片，避免每次渲染都重新计算
  const currentAvatarImage = useMemo(() => {
    const currentAvatar = avatarOptions.find(avatar => avatar.name === virtualAvatarName);
    return currentAvatar?.previewAvatarUrl || permissionConfig?.previewAvatarUrl || '';
  }, [avatarOptions, virtualAvatarName, permissionConfig]);

  // 当 currentAvatarImage 改变时，更新 store 中的 URL
  useEffect(() => {
    if (currentAvatarImage) {
      setVirtualAvatarUrl(currentAvatarImage);
    }
  }, [currentAvatarImage, setVirtualAvatarUrl]);

  const handleToggle = useCallback((checked: boolean) => {
    console.log('handleToggle', checked)
    if (!checked) {
      stop()
    }
    setVirtualAvatarEnabled(checked);
    if (onToggle) {
      onToggle(checked);
    }
  }, [setVirtualAvatarEnabled, onToggle]);

  const openModal = useCallback(() => {
    if (!isPreview) {
      setModalVisible(true);
    }
  }, [isPreview]);

  const closeModal = useCallback(() => {
    setModalVisible(false);
  }, []);

  const handleAvatarConfirm = useCallback((newAvatarName: string, newVoiceType: string, newAvatarId: string, newSpeakerId: string) => {
    setVirtualAvatarName(newAvatarName);
    setVirtualAvatarVoice(newVoiceType);
    setVirtualAvatarId(newAvatarId);

    if (onAvatarChange) {
      onAvatarChange(newAvatarName, newVoiceType, newAvatarId, newSpeakerId);
    }
  }, [setVirtualAvatarName, setVirtualAvatarVoice, onAvatarChange]);

  return (
    <div className='bg-[#F8F9FA] rounded-md my-2'>
      <div className="my-2 flex items-center justify-between rounded-md bg-[#F8F9FA] px-3 py-2">
        <div className="flex flex-col">
          <div className="flex items-center">
            <div className="mr-2 flex h-5 w-5 items-center justify-center">
              <SvgIcon icon="chat-setting-metahuman" size={18} color="var(--brand-color)" />
            </div>
            <div className="font-normal text-[#4E5969]">虚拟形象
              {!isQuota && <span className="text-xs text-text-3">（连接数已达上限，暂不支持使用）</span>}
            </div>
          </div>
          <TipDesc title={'指定该智能体关联的虚拟数字人形象、声音'} className="!mt-1" />
        </div>
        <Switch
          checked={virtualAvatarEnabled}
          onChange={handleToggle}
          className="bg-gray-300"
          disabled={isPreview || !isQuota}
        />
      </div>

      {/* 虚拟形象详情区域 */}
      {virtualAvatarEnabled && (
        <div className="mb-2 mx-2 rounded-md py-2">
          <div className="flex items-center justify-between bg-[#fff] p-1 pr-3 rounded-md">
            <div className="flex items-center">
              <div className="mr-3 rounded-md bg-transparent">
                <img
                  src={currentAvatarImage}
                  alt={virtualAvatarName}
                  className="w-12 h-12 rounded object-contain"
                  onError={(e) => { }}
                />
              </div>
              <div className="flex flex-col text-[#4E5969]">
                <div className="text-text-3">形象: <span className="text-text-5">{virtualAvatarName}</span></div>
                <div className="text-text-3">音色: <span className="text-text-5">{virtualAvatarVoice}</span></div>
              </div>
            </div>
            <Button
              type="link"
              // icon={<SettingOutlined />}
              icon={<SvgIcon icon="ai-metahuman-setting" size={16} color="var(--brand-color)" />}
              onClick={openModal}
              disabled={isPreview || loading || !isQuota}
              className="p-0 text-[#1677ff] hover:text-[#1677ff] flex items-center metahuman-setting"
            >
              设置
            </Button>
          </div>
        </div>
      )}

      {/* 虚拟形象设置弹窗 */}
      <VirtualAvatarModal
        visible={modalVisible}
        onClose={closeModal}
        avatarName={virtualAvatarName}
        voiceType={virtualAvatarVoice}
        onConfirm={handleAvatarConfirm}
        avatarOptions={avatarOptions}
      />
    </div>
  );
};

export default VirtualAvatarConfig; 